package ca.biosample.robot.serial;

import java.util.Scanner;

public class PickupTest {

	static final String CONTROL_PORT = "COM6";
	static final String COMM_PORT = "COM5";
	static final String BARCODE_PORT = "COM3";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);
		byte[] response = new byte[100];
		
		RobotInterface robot = new RobotInterface(CONTROL_PORT);
		if(!robot.isOpen()) {
			System.exit(0);
		}
		BarcodeInterface barcodeReader = new BarcodeInterface(BARCODE_PORT);
		if(barcodeReader.port == null) {
			robot.close();
			System.exit(1);
		}
		XselPort2Interface control = new XselPort2Interface(COMM_PORT);
		if(!control.isOpen()) {
			robot.close();
			barcodeReader.close();
			System.exit(1);
		}
		barcodeReader.readCode();
		robot.sendCommand("253", "20");
		int rlen = robot.robot.read(response);
		System.out.println(new String(response,0,rlen));
		String data;
		while(true) {
			try{Thread.sleep(100);}catch(Exception e){};
			data = control.readData();
			//if(quer.equals("ST?")){
			if(data.equals("BARCODE")) {
				System.out.println("Reading Barcode");
				String command;
				if(barcodeReader.readCode().contains("NOREAD"))
					command = "NO";
				else
					command = "OK";
				/*while(true) {
					System.out.print("Position? ");
					command = input.nextLine();
					if(command.equalsIgnoreCase("quit")) {
						robot.close();
						control.robot.close();
						System.exit(0);
					}
					if(command.length() != 2) {
						System.out.println("Invalid Position Number");
						continue;
					}
					int pos = Integer.parseInt(command);
					if(pos < 1 || pos > 50) {
						System.out.println("Invalid Position Number");
						continue;
					}
					break;
				}*/
				command += '\r';
				byte buf[] = null;
				try{
					System.out.println("Sending " + command);
					buf = command.getBytes("US-ASCII");
				} catch(Exception e){System.exit(1);};;
				control.robot.write(buf);
				try{Thread.sleep(100);}catch(Exception e){};
				barcodeReader.close();
				robot.close();
				control.close();
				System.exit(0);
			}
		}
	}
}
